package model

import (
	"database/sql"
	"fmt"
	"strconv"
	"strings"
)

// CURD 扩展结构体，用于链式调用
type CURD struct {
	TableName  string
	FieldsStr  string
	WhereCond  string
	OrderByStr string
	DB         *sql.DB // 假设你有一个数据库连接实例
}

// Table 设置查询表名
func (c *CURD) Table(name string) *CURD {
	c.TableName = name
	return c
}

// Fields 设置查询字段
func (c *CURD) Fields(fields string) *CURD {
	c.FieldsStr = fields
	return c
}

// Where 设置查询条件
func (c *CURD) Where(where map[string]interface{}) *CURD {
	c.WhereCond = ""
	for condition, value := range where {
		var valStr string
		switch v := value.(type) {
		case nil:
			valStr = "NULL"
		case string:
			valStr = strconv.Quote(v)
		case int, int64, float64, bool:
			valStr = fmt.Sprintf("%v", v)
		default:
			valStr = fmt.Sprintf("'%v'", v) // 兜底处理，防止格式化失败
		}
		// 判断条件中是否包含操作符
		if strings.Contains(condition, "like") {
			// 处理 LIKE 查询
			if c.WhereCond == "" {
				c.WhereCond = condition + valStr
			} else {
				c.WhereCond += " AND " + condition + valStr
			}
		} else {
			if c.WhereCond == "" {
				c.WhereCond = condition + " = " + valStr
			} else {
				c.WhereCond += " AND " + condition + " = " + valStr
			}
		}

	}
	return c
}

// OrderBy 设置排序条件
func (c *CURD) OrderBy(order string) *CURD {
	c.OrderByStr = order
	return c
}

// Select 生成并执行SQL查询
func (c *CURD) Select() (*sql.Rows, error) {
	if c.TableName == "" {
		return nil, fmt.Errorf("table name is required")
	}

	// 构建基础查询语句
	query := fmt.Sprintf("SELECT %s FROM `%s`", c.FieldsStr, c.TableName)

	// 添加 WHERE 条件
	if c.WhereCond != "" {
		query += " WHERE " + c.WhereCond
	}

	// 添加 ORDER BY 条件
	if c.OrderByStr != "" {
		query += " ORDER BY " + c.OrderByStr
	}

	fmt.Println(query)
	// 执行查询
	rows, err := c.DB.Query(query)
	if err != nil {
		return nil, fmt.Errorf("query execution failed: %v", err)
	}

	return rows, nil
}

func (c *CURD) Insert(data map[string]interface{}) (int64, error) {
	var fields []string
	var values []interface{}
	var placeholders []string

	// 构建字段和值列表
	for field, value := range data {
		fields = append(fields, field)
		values = append(values, value)
		placeholders = append(placeholders, "?")
	}

	// 构建INSERT语句
	query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)",
		c.TableName,
		strings.Join(fields, ", "),
		strings.Join(placeholders, ", "))

	// 执行插入操作
	result, err := c.DB.Exec(query, values...)

	if err != nil {
		return 0, fmt.Errorf("insert execution failed: %v", err)
	}

	// 获取插入记录的ID
	lastInsertID, err := result.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("failed to get last insert ID: %v", err)
	}

	return lastInsertID, nil
}
